#!/usr/bin/env ruby
#
#  Created by sjavey on 2007-07-07.
#  Copyright (c) 2007. All rights reserved.

require 'rexml/document'
require 'n19gpx/bounds'
require 'n19gpx/track'

module N19GPX
  class Document
    attr_reader :time
    attr_reader :bounds
    attr_reader :tracks # array of tracks
    attr_reader :max_ele
    attr_reader :min_ele
    attr_reader :start_time
    attr_reader :end_time
    attr_reader :max_point
    attr_reader :min_point
    
    def initialize(gpxfile)
      @gmt_offset = -7
      @gpxfile = gpxfile
      @xml = REXML::Document.new(File.open(@gpxfile))
      @root = @xml.root
      @time = @root.elements["time"].text
      @bounds = N19GPX::Bounds.new(@root.elements["bounds"])
      @min_ele = -1
      @max_ele = -1
      @tracks = Array.new()
      @root.elements.to_a("trk").each {|t|
        trk = N19GPX::Track.new(t) 
        @tracks << trk if trk.points.size > 0
        @min_ele = trk.min_ele if @min_ele == -1
        @max_ele = trk.max_ele if @max_ele == -1
        @min_ele = trk.min_ele if trk.min_ele < @min_ele
        @max_ele = trk.max_ele if trk.max_ele > @max_ele
        min_ele_point(trk.min_point)
        max_ele_point(trk.max_point)
      }
      @start_time = @tracks[0].points[0].time
      @end_time = @tracks[@tracks.length-1].points[@tracks[@tracks.length-1].points.length-1].time
    end 
    
    def to_hour_min(time)
      hour = time[11..12].to_i + @gmt_offset
      minute = Float(time[14..15].to_i / 60.0)
      return sprintf("%.2f", hour + minute).to_f
    end
    
    def min_ele_point(p)
      if (@min_point == nil) 
        @min_point = p
        return 
      end
      @min_point = p if (@min_point.ele > p.ele)
    end

    def max_ele_point(p)
      if (@max_point == nil) 
        @max_point = p
        return 
      end
      @max_point = p if (@max_point.ele < p.ele)
    end
    
  end
end
